//
//  ChatRoomMemberViewController.m
//  MyYiJianKangApp
//
//  Created by 张国文 on 16/4/6.
//  Copyright © 2016年 hangzhouyijiyin. All rights reserved.
//

#import "ChatRoomMemberViewController.h"
#import "CeShiModelOfFriendMessage.h"
#import "FriendMessageTableViewCell.h"
#import "SearchChatRoomMemberViewController.h"
#import "MyChatViewController.h"
#import "ZGWSearchFriendModel.h"
#import "FriendIDCheckViewController.h"


#define kCurrentUserToken [[NSUserDefaults standardUserDefaults]objectForKey:@"token"]

@interface ChatRoomMemberViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *chatRoomMemberTableView;
@property (nonatomic, strong) NSMutableArray *chatRoomMemberDataArray;
@property (nonatomic, assign) BOOL canClickGuanZhu; // 是否可以点击关注

@end

@implementation ChatRoomMemberViewController

- (void)viewWillDisappear:(BOOL)animated
{
    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    // navi的修改
    [self changeNavigation];

    // 检查网络并建立数据源
    [self searchNetAndAddData];
    self.canClickGuanZhu = YES;
}


// navi的修改
- (void)changeNavigation
{
    [self.navigationController.navigationBar setTranslucent:NO];
    self.navigationItem.title = @"聊天室成员列表";
    UIImageView *leftImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    leftImageView.image = [UIImage imageNamed:@"houtui"];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftImageView];
    UITapGestureRecognizer *leftTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lastPage:)];
    [leftImageView addGestureRecognizer:leftTapGes];
    
}

#pragma mark - 返回上一页面
- (void)lastPage:(UITapGestureRecognizer *)tapGes
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 检查网络并建立数据源
- (void)searchNetAndAddData
{
    if ([[[NetStatusHandle shareHandle] getNetStatus] isEqualToString:@"YES"]) {
        [self addData];
     
        // 开启加载动画
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
    } else {
        NSLog(@"没有网络");
        // 添加提示框
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"通知" Content:kNoNetNoRefresh ToView:self];
    }
}

#pragma mark - 建立数据源
- (void)addData
{
    // 聊天室成员列表
    NSString *chatRoomMemberListUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWChatRoomMemberList, kCurrentUserToken];
    NSDictionary *paramaterDic = @{@"chatroom_id":self.chatRoomID};
    AFHTTPSessionManager *manger = [AFHTTPSessionManager manager];
    [manger GET:chatRoomMemberListUrl parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        if (!responseObject) {
            return;
        }
        NSArray *memberArray = [NSArray arrayWithArray:responseObject];
        NSLog(@"聊天室成员:%@", memberArray);
        self.chatRoomMemberDataArray = [NSMutableArray array];
        for (NSDictionary *tempDic in memberArray) {
            ZGWSearchFriendModel *searchModel = [[ZGWSearchFriendModel alloc] init];
            [searchModel setValuesForKeysWithDictionary:tempDic];
            [self.chatRoomMemberDataArray addObject:searchModel];
        }
        // 布局
        [self addMySubview];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提示" Content:@"成员列表获取失败，请返回上页进入" ToView:self];
    }];
    
   
}

#pragma mark - 布局
- (void)addMySubview
{
    self.chatRoomMemberTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    self.chatRoomMemberTableView.backgroundColor = [UIColor whiteColor];
    self.chatRoomMemberTableView.dataSource = self;
    self.chatRoomMemberTableView.delegate = self;
    self.chatRoomMemberTableView.bounces = NO;
    self.chatRoomMemberTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_chatRoomMemberTableView];
    
    // 构造表头
    UIView *whiteBackHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 60 * kAdjustParamater)];
    whiteBackHeaderView.userInteractionEnabled = YES;
    whiteBackHeaderView.backgroundColor = [UIColor whiteColor];
    self.chatRoomMemberTableView.tableHeaderView = whiteBackHeaderView;
    
    UIImageView *searchImageV = [[UIImageView alloc] initWithFrame:CGRectMake(16 * kAdjustParamater, 17 * kAdjustParamater, 20 * kAdjustParamater, 20 * kAdjustParamater)];
    searchImageV.image = [UIImage imageNamed:@"tianjiahaoyoutubiao-tianjia"];
    [whiteBackHeaderView addSubview:searchImageV];
    
    UILabel *searchMemberLabel = [[UILabel alloc] initWithFrame:CGRectMake(searchImageV.right + 10 * kAdjustParamater, 20 * kAdjustParamater, 100 * kAdjustParamater, 11 * kAdjustParamater)];
    searchMemberLabel.userInteractionEnabled = YES;
    searchMemberLabel.text = @"输入成员名字/ID";
    searchMemberLabel.font = [UIFont systemFontOfSize:k13Big];
    searchMemberLabel.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [whiteBackHeaderView addSubview:searchMemberLabel];
    
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(searchMember:)];
    [searchMemberLabel addGestureRecognizer:tapGes];

    UILabel *grayLabelOnHeaderBottom = [[UILabel alloc] initWithFrame:CGRectMake(0, 50 * kAdjustParamater, kScreenWidth, 10 * kAdjustParamater)];
    grayLabelOnHeaderBottom.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.05];
    [whiteBackHeaderView addSubview:grayLabelOnHeaderBottom];
    
    // 表尾
    self.chatRoomMemberTableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}

#pragma mark - 搜索
- (void)searchMember:(UITapGestureRecognizer *)tapGes
{
    NSLog(@"搜索");
    SearchChatRoomMemberViewController *searchChatRoomMemberVC = [[SearchChatRoomMemberViewController alloc] init];
    searchChatRoomMemberVC.dataArray = self.chatRoomMemberDataArray;
    __block ChatRoomMemberViewController *mySelf = self;
    searchChatRoomMemberVC.zgwSearchChatRoomBlock = ^void(NSString *string) {
        [mySelf searchNetAndAddData];
    };
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:searchChatRoomMemberVC];
    [self presentViewController:naVC animated:YES completion:nil];
}

// tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.chatRoomMemberDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cell";
    FriendMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[FriendMessageTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ZGWSearchFriendModel *model = self.chatRoomMemberDataArray[indexPath.row];
    cell.zgwSearchFriendModel = model;
    [cell.attentionButton addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    cell.attentionButton.tag = 250;
    [cell.addFriendButton addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    cell.addFriendButton.tag = 251;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 75 * kAdjustParamater;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    ZGWSearchFriendModel *friendModel = self.chatRoomMemberDataArray[indexPath.row];
    NSLog(@"姓名= %@", friendModel.nikename);
    
    MyChatViewController *myChatVC = [[MyChatViewController alloc] init];
    myChatVC.conversationType = ConversationType_PRIVATE;
    myChatVC.title = friendModel.nikename;
    myChatVC.targetId = friendModel.user_id;
    [self.navigationController pushViewController:myChatVC animated:YES];
}

#pragma mark - 点击cell上的button
- (void)clickButton:(UIButton *)button
{
    UIView *view = [button superview];
    FriendMessageTableViewCell *cell = (FriendMessageTableViewCell *)[view superview];
    NSIndexPath *indexPath = [self.chatRoomMemberTableView indexPathForCell:cell];

    
    switch (button.tag) {
        case 250:
        {
            NSLog(@"row = %ld, 关注", indexPath.row);
            ZGWSearchFriendModel *searchModel = self.chatRoomMemberDataArray[indexPath.row];
            NSString *isAttention = [NSString stringWithFormat:@"%@", searchModel.is_attention];
            if ([isAttention isEqualToString:@"1"]) {
                NSLog(@"已经关注");
            } else if ([isAttention isEqualToString:@"0"]) {
                NSLog(@"进行关注");
                if (self.canClickGuanZhu == YES) {
                    self.canClickGuanZhu = NO;
                    [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] startAnimation];
                    // 关注url
                    NSString *attentionUserUrl = [NSString stringWithFormat:@"%@?token=%@", kZGWAttentionUser, kCurrentUserToken];
                    NSDictionary *paramaterDic = @{@"attention_user":searchModel.user_id};
                    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                    [manager POST:attentionUserUrl parameters:paramaterDic success:^(NSURLSessionDataTask *task, id responseObject) {
                        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
                        self.canClickGuanZhu = YES;
                        NSDictionary *statusDic = [responseObject valueForKey:@"status"];
                        NSString *msgString = [statusDic valueForKey:@"msg"];
                        if ([msgString isEqualToString:@"关注成功"]) {
                            searchModel.is_attention = [NSString stringWithFormat:@"%d", 1];
                            [self.chatRoomMemberTableView reloadData];
                        }
                    } failure:^(NSURLSessionDataTask *task, NSError *error) {
                        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] stopAnimation];
                        [[JiaZaiAnimationHandle shareJiaZaiAnimationHandle] addAlertTitle:@"提醒" Content:@"关注失败" ToView:self];
                        self.canClickGuanZhu = YES;
                    }];
                }

            }
            break;
        }
            case 251:
        {
            NSLog(@"row = %ld, 好友", indexPath.row);
            ZGWSearchFriendModel *searchModel = self.chatRoomMemberDataArray[indexPath.row];
            NSString *isFriend = [NSString stringWithFormat:@"%@", searchModel.is_friend];
            if ([isFriend isEqualToString:@"1"]) {
                NSLog(@"已经是好友");
            } else if ([isFriend isEqualToString:@"0"]) {
                NSLog(@"添加好友");
                FriendIDCheckViewController *friendIDCheckVC = [[FriendIDCheckViewController alloc] init];
                
                friendIDCheckVC.targetUserID = searchModel.user_id;
                friendIDCheckVC.currentUserName = searchModel.nikename;
                [self.navigationController pushViewController: friendIDCheckVC animated:YES];
            }
            break;
        }
        default:
            break;
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
